package com.pxml2pdf.utility;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;

public class X2pUtility {

	private static String parseStr(String str) {
		if (str == null)
			return "0";
		return str.replaceAll("px", "");
	}

	public static final Float ps2d(String str) {
		return Float.valueOf(parseStr(str));
	}

	public static final Integer ps2i(String str) {
		return Integer.parseInt(parseStr(str));
	}

	private static final String NORMAL = "normal";
	private static final String BOLD = "bold";
	private static final String RGB = "rgb";
	private static final String UNDER_LINE = "underline";
	private static final String PERCENT = "%";
	private static final float BASE_FONT_SZIE = 12f;
	private static final String EM = "em";

	private static final String CHINA_FONT = "microsoft jhenghei";
	private static final String ARIAL = "Arial";

	/**
	 * @param textDecoration
	 * @param color
	 * @param fontWeight
	 * @param fontStyle
	 * @param fontSize
	 * @param fontFamily
	 * @param fontInfo
	 * @param color
	 * @param textDecoration
	 * @param textDecoration2
	 * @param color2
	 * @param fontWeight
	 * @param hmtlFontSize
	 * @param scale
	 * @return
	 */
	public static Font getFont(String val, String fontFamily, String fontSize, String fontStyle, String fontWeight,
			String color, String textDecoration) {
		// BaseFont bfChinese = BaseFont.createFont("MHei-Medium",
		// "UniCNS-UCS2-H", BaseFont.NOT_EMBEDDED);
		// BaseFont bfChinese = BaseFont.createFont("STSong-Light",
		// "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
		Font font = FontFactory.getFont(FontFactory.COURIER);
		try {
			if (isCN(val)) {
				font = FontFactory.getFont(CHINA_FONT, BaseFont.IDENTITY_H);
			} else {
				font = FontFactory.getFont(ARIAL);
			}
		} catch (Exception e) {
			font = FontFactory.getFont(FontFactory.COURIER);
		}

		if (isItalic(fontStyle)) {
			font.setStyle(Font.ITALIC);
		}
		if (isBold(fontWeight)) {
			font.setStyle(Font.BOLD);
		}
		font.setSize(getFontSize(fontSize));
		// fontInfo = FontFactory.HELVETICA;
		// System.out.println(fontInfo);

		// font.setFamily(fontInfo);
		// System.out.println(color);
		font.setColor(getcolor(color));
		if (getUnderLine(textDecoration)) {
			font.setStyle(Font.UNDERLINE);
		}
		return font;
	}

	private static float getFontSize(String fontSize) {
		try {
			if (fontSize.indexOf(PERCENT) > 0) {
				fontSize = fontSize.replace(PERCENT, "");
				return BASE_FONT_SZIE * Float.parseFloat(fontSize);
			}
			if (fontSize.indexOf(EM) > 0) {
				fontSize = fontSize.replace(EM, "");
				return Float.parseFloat(fontSize) * 16;
			}
			return ps2d(fontSize);
		} catch (Exception e) {
			return BASE_FONT_SZIE;
		}
	}

	private static boolean isItalic(String fontStyle) {
		if (!NORMAL.equalsIgnoreCase(fontStyle)) {
			return true;
		}
		return false;
	}

	public static boolean isBold(String fontWeight) {
		if (BOLD.equalsIgnoreCase(fontWeight)) {
			return true;
		}
		if (!NORMAL.equalsIgnoreCase(fontWeight)) {
			try {
				int fw = Integer.parseInt(fontWeight);
				if (fw > 400) {
					return true;
				}
			} catch (Exception e) {
				return true;
			}
		}
		return false;
	}

	public static boolean isCN(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
				|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
				|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
				|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
			return true;
		}
		return false;
	}

	public static boolean isCN(String str) {
		if (str != null) {
			char[] csOfStr = str.toCharArray();
			for (char c : csOfStr) {
				if (isCN(c)) {
					return true;
				}
			}
		}
		return false;
	}

	public static boolean getUnderLine(String textDecoration) {
		int index = textDecoration.indexOf(" ");
		if (index >= 0) {
			return UNDER_LINE.equals(textDecoration.subSequence(0, index));
		}
		return false;
	}

	public static BaseColor getcolor(String color) {
		String str = color.substring(0, 1);
		if ("#".equals(str)) {
			if (color.length() == 4) {
				return new BaseColor(Integer.parseInt(color.substring(1, 2), 16) / 15 * 255, Integer.parseInt(
						color.substring(2, 3), 16) / 15 * 255, Integer.parseInt(color.substring(3, 4), 16) / 15 * 255);
			} else {
				return new BaseColor(Integer.parseInt(color.substring(1, 3), 16), Integer.parseInt(
						color.substring(3, 5), 16), Integer.parseInt(color.substring(5, 7), 16));
			}
		}
		str = color.substring(0, 3);
		if (RGB.equals(str)) {
			str = color.substring(color.indexOf("(") + 1, color.indexOf(")"));
			// System.out.println(str);
			String[] array1 = str.split(",");
			return new BaseColor(Integer.parseInt(array1[0].trim()), Integer.parseInt(array1[1].trim()),
					Integer.parseInt(array1[2].trim()));
		}
		return new BaseColor(255, 255, 255);
	}

	private static final String TEXT_ALIGN_RIGHT = "right";
	private static final String TEXT_ALIGN_CENTER = "center";
	private static final String TEXT_ALIGN_MIDDLE = "middle";
	private static final String TEXT_ALIGN_BOTTOM = "bottom";
	private static final String TEXT_ALIGN_TOP = "top";

	public static int convertAlign(String textAlign) {
		int align = PdfContentByte.ALIGN_LEFT;
		if (TEXT_ALIGN_RIGHT.equals(textAlign)) {
			align = PdfContentByte.ALIGN_RIGHT;
		}
		return align;
	}

	// <td align="left" valign="middle" class=" "
	// title="ADM,Gen Staff B">ADM,Gen Staff B</td>
	public static int cellAlign(String textAlign) {
		if (TEXT_ALIGN_RIGHT.equals(textAlign)) {
			return Element.ALIGN_RIGHT;
		}
		if (TEXT_ALIGN_CENTER.equals(textAlign)) {
			return Element.ALIGN_CENTER;
		}
		if (TEXT_ALIGN_MIDDLE.equals(textAlign)) {
			return Element.ALIGN_MIDDLE;
		}
		if (TEXT_ALIGN_BOTTOM.equals(textAlign)) {
			return Element.ALIGN_BOTTOM;
		}
		if (TEXT_ALIGN_TOP.equals(textAlign)) {
			return Element.ALIGN_TOP;
		}
		return Element.ALIGN_LEFT;
	}

	public static URL getIcons(String name) {
		String file = "icons/" + name;
		List<URL> list = getResources(file);
		if (list.size() > 0) {
			// System.out.print(list.get(0).getFile());
			return list.get(0);
		}
		return null;
	}

	public static List<URL> getResources(String resource) {
		// skip duplicated resources
		Set<URL> resources = new LinkedHashSet<URL>();
		collectResources(resource, X2pUtility.class.getClassLoader(), resources);
		collectResources(resource, Thread.currentThread().getContextClassLoader(), resources);
		return new ArrayList<URL>(resources);
	}

	protected static void collectResources(String resourceName, ClassLoader classLoader, Set<URL> resources) {
		if (classLoader != null) {
			try {
				for (Enumeration<URL> urls = classLoader.getResources(resourceName); urls.hasMoreElements();) {
					URL url = urls.nextElement();
					resources.add(url);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
